from flask import Flask, render_template
import mysql.connector
import os

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/generate_exam', methods=['GET'])
def generate_exam_route():
    exam_name = 'Sample Exam'
    num_choices = 2
    num_true_false = 1
    num_subjective = 2

    exam = generate_exam(exam_name, num_choices, num_true_false, num_subjective)

    if exam:
        return render_template('exam.html', exam=exam, exam_name=exam_name)
    else:
        return '生成试卷失败'

def generate_exam(exam_name, num_choices=5, num_true_false=5, num_subjective=5):
    conn = mysql.connector.connect(
        host="152.136.49.229",
        user="yuyu",
        password="123456",  # 替换为实际的数据库密码
        database="yuyude",
    )
    cursor = conn.cursor()

    try:
        # 随机选择选择题
        cursor.execute("SELECT * FROM questionsxuanze ORDER BY RAND() LIMIT %s", (num_choices,))
        choices = cursor.fetchall()

        # 随机选择判断题
        cursor.execute("SELECT * FROM question2 ORDER BY RAND() LIMIT %s", (num_true_false,))
        true_false = cursor.fetchall()

        # 随机选择主观题
        cursor.execute("SELECT * FROM questions_and_answers ORDER BY RAND() LIMIT %s", (num_subjective,))
        subjective = cursor.fetchall()

        # 保存生成的题目到 generated_exams 表
        save_generated_exams(cursor, exam_name, 'choice', choices)
        save_generated_exams(cursor, exam_name, 'true_false', true_false)
        save_generated_exams(cursor, exam_name, 'subjective', subjective)

        conn.commit()

        # 创建试卷数据
        exam = {
            'choices': choices,
            'true_false': true_false,
            'subjective': subjective
        }

    except mysql.connector.Error as err:
        print(f"Error: {err}")
        exam = None
    finally:
        cursor.close()
        conn.close()

    return exam

def save_generated_exams(cursor, exam_name, question_type, questions):
    for question in questions:
        if question_type == 'choice':
            sql = """
            INSERT INTO generated_exams (exam_name, question_type, question_text, option_a, option_b, option_c, option_d, correct_answer)
            VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
            """
            values = (
                exam_name,
                question_type,
                question[2],  # 题目
                question[3],  # 选项 A
                question[4],  # 选项 B
                question[5],  # 选项 C
                question[6],  # 选项 D
                question[7]   # 正确答案
            )
        elif question_type == 'true_false':
            sql = """
            INSERT INTO generated_exams (exam_name, question_type, question_text, correct_answer)
            VALUES (%s, %s, %s, %s)
            """
            values = (
                exam_name,
                question_type,
                question[2],  # 题目
                question[3]   # 正确答案
            )
        elif question_type == 'subjective':
            sql = """
            INSERT INTO generated_exams (exam_name, question_type, question_text, correct_answer)
            VALUES (%s, %s, %s, %s)
            """
            values = (
                exam_name,
                question_type,
                question[2],   # 题目
                question[3]  # 正确答案
            )

        cursor.execute(sql, values)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
